package com.zero.demo.jms.util;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author zengzr
 * @desc
 * @Date 2019/5/6 10:40
 */
@Component
@Log4j2
public class ApplicationContextUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        setApplicationContextLocal(applicationContext);
    }

    public static void setApplicationContextLocal(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtils.applicationContext = applicationContext;
    }

    public static <T> T getBeanAllowNull(String beanName, Class<T> type) {
        T result=null;
        try {
            result=applicationContext.getBean(beanName, type);
        } catch (NoSuchBeanDefinitionException e) {
            log.info("找不到beanId为"+beanName+"的bean!!!!");
        }
        return result;
    }
}
